"""
@name : users
@author : FengZT_19
@projectname: aishuyou
"""
from flask import request, Blueprint
from flask_restful import Resource, Api
from sqlalchemy import or_

from forms.user import UserForm, UserModifyForm
from libs.auth import login
from libs.error_code import UserException, PARAMException
from libs.handler import default_error_handler
from libs.response import generate_response
from model import db

from model.users import Users

user_bp = Blueprint("user", __name__, url_prefix="/v1")
api = Api(user_bp)

class UsersView(Resource):
    def get(self, id):
        """
        查询用户信息，通过用户id，或用户名，或手机号
        :param id: 用户id，或用户名，或手机号
        :return: 用户名、手机号、邮箱、性别、用户创建时间
        """
        if id:
            users = Users.query.filter(
                or_(Users.username.contains(id), Users.user_id.contains(id), Users.mobile.contains(id))).all()
            if users is None:
                # 否则提示用户不存在
                raise UserException

        for user in users:
            # 更改用户创建时间的输出格式
            user.user_CreateAt = user.user_CreateAt.strftime("%Y-%m-%d %H:%M:%S")
        return generate_response(message="get user success", data=[user.to_json() for user in users])

    def post(self):
        """
        新增用户
        输入：用户名，密码，重复密码，手机号，邮箱
        可选：喜欢的数据类别，性别
        :return: 用户名
        """
        data = request.json
        # 检验数据合法性
        form = UserForm(data=data)
        if form.validate():
            Users.create_user(username=form.username.data,
                              password=data["password"],
                              email=data["email"],
                              mobile=data["mobile"],
                              sex=data.get("sex", "S"))
            return generate_response(message="create user success", data=form.username.data)
        else:
            return generate_response(message=form.errors)
    @login
    def put(self, id):
        """
        需要先验证
        修改用户信息：密码（需重复输入），用户名，手机号，邮箱
        :param id:用户id
        :return:用户名
        """
        # 判断用户是否存在
        user = Users.query.get(id)
        if user:
            data = request.json
            # 检验数据合法性
            form = UserModifyForm(data=data)
            if form.validate():
                if data.get("username", 0):
                    user.username = data["username"]
                if data.get("email", 0):
                    user.email = data["email"]
                if data.get("mobile", 0):
                    user.mobile = data["mobile"]
                db.session.add(user)
                db.session.commit()
                return generate_response(message="modify user success", data=user.username)
            else:
                return generate_response(message=form.errors)
        else:
            raise UserException

    @login
    def delete(self, id):
        # 先判断是否存在用户
        user = Users.query.get(id)
        if user:
            db.session.delete(user)
            db.session.commit()
            return generate_response(message="delete user success", data=user.username)
        else:
            raise UserException


api.add_resource(UsersView, "/users")
api.add_resource(UsersView, "/users/<id>", endpoint="usersviewapi")
api.handle_error = default_error_handler
